package cn.cms.util;

import org.apache.commons.lang.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by leon on 2017/2/21.
 */
public class DateUtil {

    /**
     * 获取时间戳
     * 输出结果:1438692801766
     */
    public static long getTimeStamp() {
        Date date = new Date();
        long times = date.getTime();
        return times;
    }

    /**
     * 获取格式化的时间
     * 输出格式：2015-08-04 20:55:35
     */
    public static String getFormatDate(){
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 将时间戳转化为标准时间
     * 输出：Tue Oct 07 12:04:36 CST 2014
     */
    public static Date timestampToDate(){
        long times = 1412654676572L;
        Date date = new Date(times);
        return date;
    }
    public static Date getShortDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        return calendar.getTime();
    }

    /**
     * @Title: paseDateNoTime
     * @Description:转换Date，时间都 设置为0
     * @param date
     * @return
     * @return Date
     * @throws
     * @author wangyaoshu
     * @date 2010-12-29 上午10:52:00
     */
    public static Date paseDateNoTime(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();

    }

    /**
     *
     * @Title: paseDateNoTim
     * @Description:转换Date，时间都 设置为0
     * @param date
     * @return
     * @return String
     * @throws
     * @author wangyaoshu
     * @date 2010-12-29 上午11:16:42
     */
    public static String paseSimpleString(Date date) {
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        return time.format(date);
    }
    /**
     *
     * @Title: paseDateNoTim
     * @Description:转换Date，时间都 设置为0
     * @param date
     * @return
     * @return String
     * @throws
     * @author wangyaoshu
     * @date 2010-12-29 上午11:16:42
     */
    public static String paseDateNoTimeString(Date date) {

        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd 0:00:00");

        return time.format(date);
    }

    /**
     * String 转 Date
     *
     * @param dateString
     * @return
     * @throws ParseException
     */
    public static Date formatDate(String dateString) throws ParseException {

        String formatText = "yyyy-MM-dd HH:mm:ss";
        return formatDate(dateString, formatText);
    }

    /**
     * String 转 Date
     *
     * @param dateString
     * @param formatText
     * @return
     * @throws ParseException
     */
    public static Date formatDate(String dateString, String formatText)
            throws ParseException {
        DateFormat format = new SimpleDateFormat(formatText);
        return format.parse(dateString);
    }

    public static String getDate() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy年M月d日 ");
        String s = df.format(calendar.getTime());
        return s;
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = { "星期日 ", "星期一 ", "星期二 ", "星期三 ", "星期四 ", "星期五 ",
                "星期六 " };
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * 获得当前时间，格式yyyy-MM-dd hh:mm:ss
     *
     * @param format
     * @return
     */
    public static String getCurrentDate() {
        return getCurrentDate("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 获得当前时间，格式自定义
     *
     * @param format
     * @return
     */
    public static String getCurrentDate(String format) {
        Calendar day = Calendar.getInstance();
        day.add(Calendar.DATE, 0);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = sdf.format(day.getTime());
        return date;
    }

    public static String getCurrentDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdate = sdf.format(date);
        return sdate;
    }

    public static String getFormatDate(Date date,String format) {
        if(date == null)
            return "";
        if(format == null || format.trim().length() <= 0)
            format = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String sdate = sdf.format(date);
        return sdate;
    }

    /**
     * 获得明天时间，格式自定义
     *
     * @param format
     * @return
     */
    public static String getTomorrowDate(Date date) {
        Calendar day = Calendar.getInstance();
        day.setTime(date);
        day.add(Calendar.DATE, 1);
        day.set(Calendar.HOUR_OF_DAY, 0);
        day.set(Calendar.SECOND, 0);
        day.set(Calendar.MINUTE, 0);
        day.set(Calendar.MILLISECOND, 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdate = sdf.format(day.getTime());
        return sdate;
    }
    /**
     * 获得传递日期的第二天时间(Date格式)
     * @param date 日期参数
     * @return
     */
    public static Date getTomorrow(Date date) {
        Calendar day = Calendar.getInstance();
        day.setTime(date);
        day.add(Calendar.DATE, 1);
        day.set(Calendar.HOUR_OF_DAY, 0);
        day.set(Calendar.SECOND, 0);
        day.set(Calendar.MINUTE, 0);
        day.set(Calendar.MILLISECOND, 0);
        return day.getTime();
    }

    /**
     * 获得传递日期的第二天时间(Date格式)
     * @param date 日期参数
     * @return
     */
    public static Date getFiveDay(Date date) {
        Calendar day = Calendar.getInstance();
        day.setTime(date);
        day.add(Calendar.DATE, 5);
        day.set(Calendar.HOUR_OF_DAY, 0);
        day.set(Calendar.SECOND, 0);
        day.set(Calendar.MINUTE, 0);
        day.set(Calendar.MILLISECOND, 0);
        return day.getTime();
    }

    /**
     * 获得传递日期的第二天时间(Date格式)
     * @param date 日期参数
     * @return
     */
    public static Date getLastDay(int lastDays) {
        Calendar day = Calendar.getInstance();
        day.add(Calendar.DATE, lastDays);
        day.set(Calendar.HOUR_OF_DAY, 0);
        day.set(Calendar.SECOND, 0);
        day.set(Calendar.MINUTE, 0);
        day.set(Calendar.MILLISECOND, 0);
        return day.getTime();
    }

    /**
     * 获得传递日期的第二天时间(Date格式)
     * @param date 日期参数
     * @return
     */
    public static Date getFourDay(Date date) {
        Calendar day = Calendar.getInstance();
        day.setTime(date);
        day.add(Calendar.DATE, 4);
        day.set(Calendar.HOUR_OF_DAY, 0);
        day.set(Calendar.SECOND, 0);
        day.set(Calendar.MINUTE, 0);
        day.set(Calendar.MILLISECOND, 0);
        return day.getTime();
    }

    /**
     * 获得昨天时间，格式自定义
     *
     * @param format
     * @return
     */
    public static String getYesterdayDate(String format) {
        Calendar day = Calendar.getInstance();
        day.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = sdf.format(day.getTime());
        return date;
    }

    /**
     * @param date1
     *            需要比较的时间 不能为空(null),需要正确的日期格式 ,如：2009-09-12
     * @param date2
     *            被比较的时间 为空(null)则为当前时间
     * @param stype
     *            返回值类型 0为多少天，1为多少个月，2为多少年
     * @return 举例： compareDate("2009-09-12", null, 0);//比较天
     *         compareDate("2009-09-12", null, 1);//比较月
     *         compareDate("2009-09-12", null, 2);//比较年
     */
    public static int compareDate(String startDay, String endDay, int stype) {
        int n = 0;
        @SuppressWarnings("unused")
        String[] u = { "天", "月", "年" };
        String formatStyle = stype == 1 ? "yyyy-MM" : "yyyy-MM-dd";

        endDay = endDay == null ? getCurrentDate("yyyy-MM-dd") : endDay;

        DateFormat df = new SimpleDateFormat(formatStyle);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(startDay));
            c2.setTime(df.parse(endDay));
        } catch (Exception e3) {
        }
        while (!c1.after(c2)) { // 循环对比，直到相等，n 就是所要的结果
            n++;
            if (stype == 1) {
                c1.add(Calendar.MONTH, 1); // 比较月份，月份+1
            } else {
                c1.add(Calendar.DATE, 1); // 比较天数，日期+1
            }
        }
        n = n - 1;
        if (stype == 2) {
            n = n / 365;
        }
        return n;
    }

    public static int timeCompare(String pgTime, String timeNow) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        try {
            Date dtStart = df.parse(pgTime);
            Date dtNow = df.parse(timeNow);
            if (dtStart.getTime() > dtNow.getTime()) {
                return 1;	//未开始（开始时间大于当前时间）
            } else {
                return 2;	//直播中（当前时间大于当前时间小于结束时间）
            }
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 判断时间是否符合时间格式
     */
    public static boolean isDate(String date, String dateFormat) {
        if (date != null) {
            java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
                    dateFormat);
            format.setLenient(false);
            try {
                format.format(format.parse(date));
            } catch (ParseException e) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 判断时间是否符合时间格式
     */
    public static boolean isToday(Date date) {
        if (date != null)
        {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String u = df.format(date);
            String n = df.format(Calendar.getInstance().getTime());
            if(n.equals(u))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 实现给定某日期，判断是星期几 date:必须yyyy-MM-dd格式
     */
    public static String getWeekday(String date) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdw = new SimpleDateFormat("E");
        Date d = null;
        try {
            d = sd.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sdw.format(d);
    }

    /**
     * 用来全局控制 上一周，本周，下一周的周数变化
     */
    private static int weeks = 0;

    /**
     * 获得当前日期与本周一相差的天数
     */
    private static int getMondayPlus() {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return -6;
        } else {
            return 2 - dayOfWeek;
        }
    }

    /**
     * 获得本周星期一的日期
     */
    public static String getCurrentMonday(String format) {
        weeks = 0;
        int mondayPlus = getMondayPlus();
        Calendar currentDate = Calendar.getInstance();
        currentDate.add(Calendar.DATE, mondayPlus);
        SimpleDateFormat sdf = new SimpleDateFormat(format);// "yyyy-MM-dd"
        String date = sdf.format(currentDate.getTime());
        return date;
    }

    /**
     * 获得上周星期一的日期
     */
    public static String getPreviousMonday(String format) {
        weeks--;
        int mondayPlus = getMondayPlus();
        Calendar currentDate = Calendar.getInstance();
        currentDate.add(Calendar.DATE, mondayPlus + 7 * weeks);
        SimpleDateFormat sdf = new SimpleDateFormat(format);// "yyyy-MM-dd"
        String date = sdf.format(currentDate.getTime());
        return date;
    }

    /**
     * 获得下周星期一的日期
     */
    public static String getNextMonday(String format) {
        weeks++;
        int mondayPlus = getMondayPlus();
        Calendar currentDate = Calendar.getInstance();
        currentDate.add(Calendar.DATE, mondayPlus + 7 * weeks);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = sdf.format(currentDate.getTime());
        return date;
    }

    /**
     * 获得相应周的周日的日期 此方法必须写在getCurrentMonday，getPreviousMonday或getNextMonday方法之后
     */
    public static String getSunday(String format) {
        int mondayPlus = getMondayPlus();
        Calendar currentDate = Calendar.getInstance();
        currentDate.add(Calendar.DATE, mondayPlus + 7 * weeks + 6);
        SimpleDateFormat sdf = new SimpleDateFormat(format);// "yyyy-MM-dd"
        String date = sdf.format(currentDate.getTime());
        return date;
    }

    /**
     *method 将字符串类型的日期转换为一个timestamp（时间戳记java.sql.Timestamp）
     *
     * @param dateString
     *            需要转换为timestamp的字符串
     *@return dataTime timestamp
     */
    public final static java.sql.Timestamp string2Time(String dateString) {
        DateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
        dateFormat.setLenient(false);
        java.util.Date date = null;
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new java.sql.Timestamp(date.getTime());
    }

    /**
     *method 将字符串类型的日期转换为一个Date（java.sql.Date）
     *
     * @param dateString
     *            需要转换为Date的字符串
     *@return dataTime Date
     */
    public final static java.sql.Date string2Date(String dateString) {
        DateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        dateFormat.setLenient(false);
        java.util.Date date = null;
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new java.sql.Date(date.getTime());
    }

    /**
     *记录考勤， 记录迟到、早退时间
     *
     * @return
     */
    public static String getState() {
        String state = "正常";
        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        Date d = new Date();
        try {
            Date d1 = df.parse("08:00:00");
            Date d2 = df.parse(df.format(d));
            Date d3 = df.parse("18:00:00");
            int t1 = (int) d1.getTime();
            int t2 = (int) d2.getTime();
            int t3 = (int) d3.getTime();
            if (t2 < t1) {
                long between = (t1 - t2) / 1000;
                long hour1 = between % (24 * 3600) / 3600;
                long minute1 = between % 3600 / 60;
                state = "迟到 ：" + hour1 + "时" + minute1 + "分";
            } else if (t2 < t3) {
                long between = (t3 - t2) / 1000;
                long hour1 = between % (24 * 3600) / 3600;
                long minute1 = between % 3600 / 60;
                state = "早退 ：" + hour1 + "时" + minute1 + "分";
            }
            return state;
        } catch (Exception e) {
            return state;
        }
    }

    /**
     * 获取就近十五年
     */
    public static List<Map<String, String>> getyears() {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Calendar cd = Calendar.getInstance();
        int year = cd.get(Calendar.YEAR);
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("name", String.valueOf(year));

        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("name", String.valueOf(year-1));

        Map<String, String> map3 = new HashMap<String, String>();
        map3.put("name", String.valueOf(year-2));

        Map<String, String> map4 = new HashMap<String, String>();
        map4.put("name", String.valueOf(year-3));

        Map<String, String> map5 = new HashMap<String, String>();
        map5.put("name", String.valueOf(year-4));

        Map<String, String> map6 = new HashMap<String, String>();
        map6.put("name", String.valueOf(year-5));

        Map<String, String> map7 = new HashMap<String, String>();
        map7.put("name", String.valueOf(year-6));

        Map<String, String> map8 = new HashMap<String, String>();
        map8.put("name", String.valueOf(year-7));

        Map<String, String> map9 = new HashMap<String, String>();
        map9.put("name", String.valueOf(year-8));

        Map<String, String> map10 = new HashMap<String, String>();
        map10.put("name", String.valueOf(year-9));

        Map<String, String> map11 = new HashMap<String, String>();
        map11.put("name", String.valueOf(year-10));

        Map<String, String> map12 = new HashMap<String, String>();
        map12.put("name", String.valueOf(year-11));

        Map<String, String> map13 = new HashMap<String, String>();
        map13.put("name", String.valueOf(year-12));

        Map<String, String> map14 = new HashMap<String, String>();
        map14.put("name", String.valueOf(year-13));

        Map<String, String> map15 = new HashMap<String, String>();
        map15.put("name", String.valueOf(year-14));

        Map<String, String> map16 = new HashMap<String, String>();
        map16.put("name", String.valueOf(year-15));
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        list.add(map5);
        list.add(map6);
        list.add(map7);
        list.add(map8);
        list.add(map9);
        list.add(map10);
        list.add(map11);
        list.add(map12);
        list.add(map13);
        list.add(map14);
        list.add(map15);
        list.add(map16);
        return list;
    }

    /**
     * 获取时间的长字符串形式 "yyyy-MM-dd HH:mm:ss"
     */
    public static String ymdHms(Date date) {
        return getFormatDate(date, "yyyy-MM-dd HH:mm:ss");
    }
    public static String mmStyle(String mm){
        if(StringUtils.isBlank(mm)){
            return "";
        }
        if(mm.indexOf(":") >= 0){
            return mm;
        }else{
            mm=mm.replace("分", "");
            int f=Integer.parseInt(mm);
            int h = f/60;
            int m = f%60;
            //int m = f/60;
            if(h==0){
                mm="00:";
            }else if(h <10){
                mm="0"+h+":";
            }else{
                mm=h+":";
            }
            if(f<10){
                mm+="0"+m+":00";
            }else{
                mm+=m+":00";
            }
            return mm;
        }
    }

    public static String polishingFormat(String date)
    {
        try
        {
            DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            DateFormat format2 = new SimpleDateFormat("yyyyMMdd");
            return format2.format(format.parse(date));
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return date;
        }
    }
}
